// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 保存、更新公告
 */
exports.main = async (event, context) => {
  try {
    const { OPENID } = cloud.getWXContext()
    // 查看当前用户在编辑的notice记录
    const res = await db.collection('notice')
      .where({ _openid: OPENID, status: 0 })
      .get()
    if (res.data && res.data.length > 0) {
      // 如果存在则直接返回
      return {
        code: 0,
        data: res.data[0]
      }
    } else {
      // 如果不存在，则新曾一条记录并返回
      const res = await db.collection('notice')
        .add({ data: { _openid: OPENID, status: 0 } })
      return {
        code: 0,
        data: {
          _id: res._id,
          _openid: OPENID,
          status: 0
        }
      }
    }
  } catch (err) {
    return {
      code: -1,
      error: err
    }
  }
}